package com.xiyun.f1101t1200;

import java.util.concurrent.Semaphore;

public class SortPrint_1114 {
    public static void resolve(String[] args) throws InterruptedException {
        Foo foo = new Foo();
        int[] arr = new int[]{1, 3, 2};
        for (int i : arr) {
            switch (i) {
                case 1:
                    new Thread(()->{
                        try {
                            foo.first(() -> {
                                System.out.println("first");
                            });
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
                    break;
                case 2:
                    new Thread(()->{
                        try {
                            foo.second(() -> {
                                System.out.println("second");
                            });
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
                    break;
                case 3:
                    new Thread(()->{
                        try {
                            foo.third(() -> {
                                System.out.println("third");
                            });
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
            }
        }
    }
}

class Foo {

    Semaphore semaphore1 = new Semaphore(0);
    Semaphore semaphore2 = new Semaphore(0);

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        semaphore1.release();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        semaphore1.acquire();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        semaphore2.release();
    }

    public void third(Runnable printThird) throws InterruptedException {
        semaphore2.acquire();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
//        semaphore2.release();
    }
}